auto.waitFor();  // 无障碍服务是否已经启用

console.show()


// 封装的时间戳转换日期函数
function dateTrans(date) {
    let _date = new Date(parseInt(date));
    let y = _date.getFullYear(); 
    let m = _date.getMonth() + 1; 
    m = m < 10 ? ('0' + m) : m;
    let d = _date.getDate(); 
   d = d < 10 ? ('0' + d) : d;
   let h = _date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = _date.getMinutes(); 
    let second = _date.getSeconds(); 
     minute = minute < 10 ? ('0' + minute) : minute; second = second < 10 ? ('0' + second) : second; 
   // console.log( y + '-' + m + '-' + d + ' ' + '　' + h + ':' + minute + ':' + second) 
    // let dates = y + '-' + m + '-' + d + '-' + h + '-' + minute;
    let dates = h + ':' + minute;
    //log(dates)
    return dates;
}

function update_time(){
    storage.put('last_time', Date.parse(new  Date())/1000);
}

function logger(txt){
    toastLog(txt)
    //console.trace(txt);
    //toast(txt)
}

function kill(packageName){
    log('杀掉进程')
    // 关闭app
    for (let index = 0; index < 6; index++) {
        if (currentPackage() == packageName){
            back();
            log(currentPackage())
            if(currentPackage() != packageName){
                return true
            }
            sleep(300)
        }
    }
}

function r_tap(uiobj){
    // 点击函数
    try {
        //toast([uiobj.bounds().centerX(), uiobj.bounds().centerY()])
        //Tap(uiobj.bounds().centerX(), uiobj.bounds().centerY());
        click(uiobj.bounds().centerX(), uiobj.bounds().centerY());
    } catch (error) {
        log(error)
    }
}

//初始化
function init() {
    log('启动微商相册')
    launchApp('微商相册')
    sleep(5000)
    for (let x = 0; x < 30; x++) {
        if(id("com.truedian.dragon:id/tab_txt").text("已关注").exists()){
            log('初始化成功')
            return true
        }else if(text('不保留').exists()){
            text('不保留').findOne().click()
        }else{
            back()
            sleep(5000)
        }
    }
    log('初始化失败')
    return false
}

//进入商品列表界面
function open_page(){
    id("com.truedian.dragon:id/tab_txt").text("已关注").findOne().parent().click()
    textStartsWith('我的相册').findOne().click()
    for (let x = 0; x < 10; x++) {
        if(text('批量转发/编辑').exists()){
            log('进入列表界面成功')
            return true
        }else{
            sleep(1000)
        }
    }
    log('进入列表界面失败')
    return false
}

//发送一个商品
function send_one(txt){
    logger('开始操作')
    update_time()
    text(txt).findOne().click()
    log('已发布数量:' + done_list.length)
    log('发布:' + txt)
    sleep(5000)
    for (let s = 0; s < 10; s++) {
        text('一键分享').findOne().click()
        sleep(2000)
        if(text('朋友圈').visibleToUser().exists()){
            break
        }else{
            sleep(2000)
        }
    }
    text('朋友圈').findOne().parent().click()
    sleep(5000)
    for (let x = 0; x < 20; x++) {
        if(text('发表').exists()){
            text('发表').findOne().click()
            sleep(6000)
            for (let y = 0; y < 20; y++) {
                if(text('朋友圈').exists()){
                    back()
                    for (let s = 0; s < 10; s++) {
                        if(id('com.truedian.dragon:id/icon_back').exists()){
                            break
                        }else if(text('批量转发/编辑').exists()){
                            break
                        }else{
                            back()
                            sleep(3000)
                        }
                    }
                    if(id('com.truedian.dragon:id/icon_back').exists()){
                        id('com.truedian.dragon:id/icon_back').findOne().click()
                    }
                    sleep(1000)
                    return true
                }else{
                    sleep(1000)
                }
            }
        }else{
            sleep(1000)
        }
    }
    return false
}

function jb_one(){
    while(true){
        logger('循环中')
        update_time()
        if(text('详情').exists()){
            id('com.truedian.dragon:id/icon_back').findOne().click()
            sleep(1000)
        }
        var items = id('com.truedian.dragon:id/title_home_fragment').visibleToUser().find()
        for (let x = 0; x < items.length; x++) {
            if(done_list.indexOf(items[x].text()) >= 0 ){
                continue
            }else{
                if(send_one(items[x].text())){
                    done_list.push(items[x].text())
                    storage.put('done_list', done_list)
                }
            }
        }
        if(text('没有更多数据了=.=!').visibleToUser().exists()){
            is_over = true
            done_list = []
            storage.put('done_list', done_list)
            return true
        }else{
            swipe(device.width * 0.8, device.height * 0.8 , device.width * 0.8, device.height * 0.3, 1500)
            sleep(3000)
        }
    }
}



function jb(){
    while(true){
        while(true){
            if(!is_over){
                logger('任务没有完成，继续操作')
                break
            }
            is_start = false
            for (let x = 0; x < time_list.length; x++) {
                log(dateTrans(new Date().getTime()) + ' - ' + time_list[x])
                if(dateTrans(new Date().getTime()) == time_list[x]){
                    log('开始此轮操作')
                    is_start = true
                    break
                }
            }
            if(is_start){
                break
            }
            update_time()
            sleep(58*1000)
        }
        is_over = false
        init()
        open_page()
        while(true){
            if(jb_one()){
                log('此轮循环操作完成')
                break
            }
        }
    }
}


var storage = storages.create("WSXC");

done_list = storage.get('done_list')
if(done_list == undefined){
    done_list = []
}

var time_list = storage.get('time_list');
is_over = true




var jb_t = threads.start(jb);
var now;
var old;


update_time()



while(true){
    now =  Date.parse(new  Date())/1000;
    old = storage.get('last_time');
    if (now - old > 120){
        logger('卡死检测:检测到卡死，重启任务');
        jb_t.interrupt();
        jb_t = threads.start(jb);
        sleep(30 * 1000);
    }else{
        logger('卡死检测:运行正常, 检测间隔:' + (now - old));
        sleep(30 * 1000);
    } 
}